<template>
    <a-sub-menu key="sub4">
        <template #title>视频监控</template>
        <a-menu-item key="setting:9" @click="viewMonitor">查看监控</a-menu-item>
        <a-menu-item key="setting:10" @click="removeMonitor">取消查看</a-menu-item>
    </a-sub-menu>
</template>
<script setup>
import { Query } from 'assets/libs/utils/ES6Query.js'
import { ref, computed } from 'vue';
import { useMapStore } from 'stores/mapStore.js'
/* 实现地图响应式 */
const store = useMapStore();
const map = computed(() => store.map)
/* 标记监控状态防止重复点击 */
let flag = false
/* 矢量数据源 */
var sourceCamera = new ol.source.Vector({
    wrapX: false,
});
/* 矢量图层及样式 */
const layerCamera = ref(new ol.layer.Vector({
    source: sourceCamera,
    style: new ol.style.Style({
        image: new ol.style.Icon({
            anchor: [0.3, 50],
            anchorOrigin: 'bottom-right',
            anchorXUnits: 'fraction',
            anchorYUnits: 'pixels',
            offsetOrigin: 'top-right',
            // offset:[0,10],
            //图标缩放比例
            scale: 0.12,
            //透明度
            opacity: 1,
            //图标的url
            src: '/src/assets/images/camera.png',
        }),
    }),
}))
function removeMonitor() {
    flag = false
    // console.log(map.value.getLayers());
    sourceCamera.clear()
    // sourceCamera = null
    // map.value.removeLayer(map.value.getLayers().getArray()[3]);
    map.value.removeLayer(layerCamera.value)
    ol.Observable.unByKey(key); //移除点击事件
    ol.Observable.unByKey(mouseMoveKey); //移除鼠标移动事件
    //console.log(map.value.getLayers()); 
}
let key; //标记地图点击事件
let mouseMoveKey //标记鼠标移动事件
const viewMonitor = () => {
    // console.log(map.value);

    if (flag == false) {
        flag = true
        // console.log("看监控");
        Query.queryByLayerID(
            {
                service: {
                    docName: "guanggu",
                    layerId: 3
                },
                callback: (result) => {
                    // console.log(result);
                    //初始化Zondy.Format.PolygonJSON类
                    var format = new Zondy.Format.PolygonJSON();
                    //将MapGIS要素JSON反序列化为ol.Feature类型数组
                    var monitorFeatures = format.read(result);
                    sourceCamera.addFeatures(monitorFeatures);
                    /* 将查询到的要素标注显示(摄像头) */
                    map.value.addLayer(layerCamera.value);
                    /* ------------------------------------------------ */
                    /**
                     * 实现popup的html元素
                     */
                    var container = document.getElementById('popup');
                    var content = document.getElementById('popup-content');
                    var closer = document.getElementById('popup-closer');
                    const popup = new ol.Overlay({
                        /** @type {olx.OverlayOptions} */
                        //要转换成overlay的HTML元素
                        element: container,
                        //当前窗口可见
                        autoPan: true,
                        //Popup放置的位置
                        positioning: 'bottom-center',
                        //是否应该停止事件传播到地图窗口
                        stopEvent: false,
                        autoPanAnimation: {
                            //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
                            duration: 250,
                        },
                    });
                    map.value.addOverlay(popup);

                    //添加关闭按钮的单击事件（隐藏popup）
                    closer.onclick = function () {
                        //未定义popup位置
                        popup.setPosition(undefined);
                        //失去焦点
                        closer.blur();
                        return false;
                    };
                    /**
                     * 动态创建popup的具体内容
                     * @param {string} title
                     */
                    function addFeatrueInfo(info) {
                        //新增标题元素存放监控器编号
                        var elementA = document.createElement('h3');
                        elementA.style.background = '#2196f3';
                        elementA.style.padding = '5px 10px';
                        elementA.style.height = '35px';
                        elementA.style.color = '#fff';
                        setInnerText(elementA, info.att.title);
                        // 新建的div元素添加A子节点
                        content.appendChild(elementA);
                        //新增标题元素存放监控器地址元素
                        var elementDiv = document.createElement('div');
                        elementDiv.style.margin = '10px 0 0 0';
                        // 为content添加div子节点;
                        var elPositionName = document.createElement('span');
                        elPositionName.innerText = '位置：';
                        //--- 位置样式---
                        elPositionName.style.display = 'inline-block';
                        elPositionName.style.padding = '0 0 10px 0';
                        elPositionName.style.fontWeight = '700';
                        var elPositionContent = document.createElement('span');
                        elPositionContent.innerText = info.att.text;
                        elPositionContent.style.display = 'inline-block';
                        elPositionContent.style.padding = '5px 0';
                        elementDiv.appendChild(elPositionName);
                        elementDiv.appendChild(elPositionContent);
                        content.appendChild(elementDiv);
                        //新增video元素，播放视频
                        var elementVideo = document.createElement('video');
                        // elementVideo.style.padding = '10px 10px';
                        // elementVideo.style.border = ' 1px solid rgb(189, 181, 181)';
                        elementVideo.autoplay = true;
                        elementVideo.style.width = "320px";
                        elementVideo.style.height = "180px";
                        elementVideo.controls = true;
                        elementVideo.src = info.att.videoUrl;
                        // 为content添加img子节点
                        content.appendChild(elementVideo);
                    }

                    /**
                     * 动态设置元素文本内容（兼容）
                     */
                    function setInnerText(element, text) {
                        if (typeof element.textContent == 'string') {
                            element.textContent = text;
                        } else {
                            element.innerText = text;
                        }
                    }
                    // 为map添加点击事件监听，渲染弹出popup
                    key = map.value.on('click', function (evt) {
                        //判断当前单击处是否有要素，捕获到要素时弹出popup
                        var monitorFeature = map.value.forEachFeatureAtPixel(
                            evt.pixel,
                            function (monitorFeature, layer) {
                                return monitorFeature;
                            }
                        );
                        if (monitorFeature) {
                            /* 判断是否存在obj,不能和监控图层冲突 */
                            var obj = monitorFeature.values_.values_ ? monitorFeature.values_.values_ : false
                            if (obj) {
                                //示例标注点的信息对象
                                var featuerInfo = {
                                    geo: monitorFeature,
                                    att: {
                                        //标注信息的标题内容
                                        title: '摄像头：' + obj.编号,
                                        //标注详细信息链接
                                        titleURL: 'http://www.openlayers.org/',
                                        //标注内容简介
                                        text: obj.位置,
                                        //标注的图片
                                        videoUrl: '/src/assets/videos/monitor.mp4',
                                    },
                                };

                                //清空popup的内容容器
                                content.innerHTML = '';
                                //在popup中加载当前要素的具体信息
                                addFeatrueInfo(featuerInfo);
                                if (popup.getPosition() == undefined) {
                                    //设置popup的位置, 此时还未打开过popup弹窗
                                    let position = monitorFeature.getGeometry().getCoordinates()[0];
                                    popup.setPosition(position);
                                } else {
                                    // 如果feature的为新点击的对象, 则赋予popup新的显示位置
                                    let position = monitorFeature.getGeometry().getCoordinates()[0];
                                    popup.setPosition(position);
                                }
                            }
                        }
                    });
                    // 为map添加鼠标移动事件监听，当指向标注时改变鼠标光标状态
                    mouseMoveKey = map.value.on('pointermove', function (e) {
                        // console.log("移动了");
                        // console.log(e.originalEvent);
                        var pixel = map.value.getEventPixel(e.originalEvent);
                        var hit = map.value.hasFeatureAtPixel(pixel);
                        map.value.getTargetElement().style.cursor = hit ? 'pointer' : '';
                    });
                }
            }

        )
    }

}
</script> 
<style>
/* --------------popup弹窗------------------- */
/* popup弹窗 */
.ol-popup {
    position: absolute;
    background-color: white;
    -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    padding: 0px;
    border-radius: 10px;
    border: 1px solid #cccccc;
    bottom: 45px;
    left: -50px;
}

.ol-popup:after,
.ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: ' ';
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}

.ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
}

.ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
}

.ol-popup-closer:after {
    position: absolute;
    content: "X";
    color: #fff;
    font-size: 25px;
    top: 15px;
    right: 25px;
}

.ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 2px;
    right: 8px;
}

#popup-content {
    padding: 20px;
    padding-bottom: 10px;
    font-size: 14px;
    font-family: '微软雅黑';
}

#popup-content > h5 {
    background: #2196f3;
}
</style>